import logging

import pytest

from Determining_ad.src.Tools import ad_threading
from Determining_ad.src.Tools.custom_assert import get_instance

from Determining_ad.src.Others_ad.others_log_start import others_ad_log_start
from Determining_ad.src.HaiNan_ad.hainan_log_start import hn_ad_log_start


@pytest.fixture(scope="class", autouse=True)
def set_global_variable1(request):
    """类级别自动执行的全局数据准备"""
    try:
        request.cls.all_df, request.cls.ad_df, request.cls.entity = (
            ad_threading.ad_log_thread()
        )

    except TypeError as e:
        logging.error(f"获取所有df为空：{e}")
        raise

    # 动态生成不同实体的数据集
    entity_map = {
        'bj': {
            'video': others_ad_log_start.get_video_ad,
            'video50': others_ad_log_start.get_video50_ad,
            'first': others_ad_log_start.get_main_ad,
            'second': others_ad_log_start.get_second_ad,
            'quit': others_ad_log_start.get_quit_ad,
            'quit_second': others_ad_log_start.get_second_quit_ad,
            'pool': others_ad_log_start.get_pool_ad
        },
        'hn': {
            'video': hn_ad_log_start.get_video_ad,
            'video50': hn_ad_log_start.get_video50_ad,
            'first': hn_ad_log_start.get_main_ad,
            'second': hn_ad_log_start.get_second_ad,
            'quit': hn_ad_log_start.get_quit_ad,
            'quit_second': hn_ad_log_start.get_second_quit_ad,
            'pool': hn_ad_log_start.get_pool_ad
        }
    }
    processor = entity_map.get(request.cls.entity)
    if processor:
        request.cls.pool_df = processor['pool'](request.cls.ad_df)
        request.cls.video_df = processor['video'](request.cls.ad_df)
        request.cls.video50_df = processor['video50'](request.cls.ad_df)
        request.cls.first_df = processor['first'](request.cls.ad_df)
        request.cls.second_df = processor['second'](request.cls.ad_df)
        request.cls.quit_df = processor['quit'](request.cls.ad_df)
        request.cls.quit_second_df = processor['quit_second'](request.cls.ad_df)


@pytest.fixture(scope="function")
def custom_error():
    """
    被标记为fixtrue的函数
    创建 CustomAssert的实例，供测试方法使用（1、自定义断言   2、将error列表清空）
    """
    instance = get_instance()
    return instance


@pytest.fixture(scope="function", autouse=True)
def check_sp(custom_error, request):
    """
    是前置操作：检查 sp 是否为空
    :param custom_error: 自定义错误处理工具
    :param request: request 是 pytest 提供的一个内置对象，用于在 fixture 中访问与当前测试相关的上下文信息
    """
    type_list = ['4', '6', '0', '35', '36', '1']
    empty_values = ['', '0']

    # 获取当前测试类实例，并且获取ad_df属性
    ad_df = request.instance.ad_df

    # 筛选出符合条件的行
    ad_df = ad_df[ad_df['adType'].isin(type_list) & ad_df['sp'].isin(empty_values)]

    if ad_df.empty:
        custom_error.custom_assert(True, success_message="sp正确")
    else:
        custom_error.custom_assert(False, failure_message="sp不正确")
        result = ad_df[['adId', 'adParam', 'adOrderNo', 'sp']].drop_duplicates(subset=['adOrderNo', 'adParam'])
        logging.debug(f"未上报的sp:\n{result}")


@pytest.fixture(scope="function", autouse=True)
def check_TypeError(custom_error, request):
    """
    是前置操作：检查是否存在报错TypeError
    :param custom_error:
    :param request:
    :return:
    """
    error = 'TypeError'
    # 遍历Message中是否存在TypeError
    # 获取当前测试类实例，并且获取ad_df属性
    all_df = request.instance.all_df

    mask = all_df['Message'].str.contains(error, case=True, na=False)

    # 结果判断
    if mask.any():
        custom_error.custom_assert(False, failure_message=f"存在{error}")
        logging.debug(f"上报的{error}：\n{all_df[mask].to_string()}")
    else:
        custom_error.custom_assert(True, success_message=f"不存在{error}")
